import sdk from 'jweixin-npm';
/**
 * 
 */
export default {
	sdk: sdk,
	/**
	 * 判断是否为微信客户端
	 * @returns {boolean}
	 */
	clientCheckFunc() {
		const ua = window.navigator.userAgent.toLowerCase()
		if (ua.match(/MicroMessenger/i) == 'micromessenger') { // eslint-disable-line
			return true
		}
		return false
	},
	/**
	 * 微信登陆
	 */
	loginFunc(id, login_link, login_scope, success_redirect, error_redirect) {
		// 授权公众号ID
		id = parseInt(id) || 0;
		// 当前链接
		let nowLink = window.location.href;
        // alert(nowLink)
		if (!id) {
			console.log('公众号配置错误')
			// 进行安全处理
			let safeLink = nowLink.replace(/[?|&]wx_id=[%+-_0-9a-zA-z]*/, '');
			if (nowLink !== safeLink) {
				// 清除历史记录，避免回退
				window.history.forward(1);
				window.location.href = safeLink;
			}
			return null;
		}
		let loginStatus = this.loginCheckFunc(id);
        // alert(loginStatus)
		console.log('登陆状态：', loginStatus);
		if (loginStatus) {
			return loginStatus;
		}
		let redirectLink = login_link || '';
        // alert(redirectLink)
		if (!redirectLink) {
			console.log('登陆配置错误');
			return null;
		}
		// 跳转到授权页
		if (login_scope != 'snsapi_message') {
			redirectLink += redirectLink.indexOf('?') == -1 ? '?' : '&';
			redirectLink += 'wx_id=' + id + '&wx_scope=' + login_scope;
			if (success_redirect) { // 成功回调
				redirectLink += '&wx_success=' + btoa(encodeURI(success_redirect));
			} else { // 回调到当前页
				redirectLink += '&wx_success=' + btoa(encodeURI(nowLink));
			}
			if (error_redirect) {
				redirectLink += '&wx_error=' + btoa(encodeURI(error_redirect));
			}
		}
		console.log('登陆地址：', redirectLink);
		window.location.href = redirectLink;
		return null;
	},
	loginCheckFunc(id) {
		// 取得登陆微信ID，链接植入优先
		id = this.getQueryStringFunc('wx_id') || id;
		if (!id) {
			return false;
		}
		// 取得本地TOKEN
		let vuex_token = uni.getStorageSync('vuex_wx_token') || '';
		// 取得授权TOKEN
		let link_token = this.getQueryStringFunc('wx_token') || '';
		// 定义返回TOKEN
		let token = link_token || vuex_token;
		// 判断是否登陆
		if (!token) {
			return false;
		}
		// 更新TOKEN
		if (link_token && link_token != vuex_token) {
			uni.setStorageSync('vuex_wx_token', link_token);
			// 进行安全处理
			let nowLink = window.location.href;
			let safeLink = nowLink.replace(/[?|&]wx_token=[%+-_0-9a-zA-z]*/, '');
			if (nowLink !== safeLink) {
				// 清除历史记录，避免回退
				window.history.forward(1);
				window.location.href = safeLink;
			}
		}
		return {
			id: id,
			token: token
		}
	},
	/**
	 * 获取链接参数
	 * @param {Object} name
	 */
	getQueryStringFunc(name) {
		if ((new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')).test(window.location.href)) {
			return unescape(RegExp.$2.replace(/\+/g, ''));
		}
		return false;
	}
}
